package com.kaifamiao.wendao.dao;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import com.kaifamiao.wendao.entity.Topic;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ExplainDao extends BaseDao<Explain, Long> {

    private static final String SELECT_BASE="select id, customer_id, publish_time, publish_address, topic_id, content, praise,despise from t_explains";
    public final static String SELECT_ONE = SELECT_BASE +" where id = ?";
    public final static String SELECT_TOPIC_ID = SELECT_BASE +" where topic_id= ?";
    private static final String SELECT_ALL = SELECT_BASE + " order by id ";
    public final static String SELECT_MAX_ID ="select max(id) from t_explains";
    public final static String INSERT_ONE = "insert into t_explains (id, content, publish_time, publish_address, topic_id, customer_id) values (?,?,?,?,?,?)";
    private static final String UPDATE_ONE = " update t_explains set content=?,praise=?, despise=? where id=?";
    private final static String DELETE_ONE = "delete from t_explains where id = ?";
    private static final String DELETE_BY_TOPIC_ID = "DELETE FROM t_explains WHERE topic_id = ?";


    public Explain wrap(ResultSet rs) throws SQLException {
        Explain e= new Explain();
        e.setId(rs.getLong("id"));
        long cid = rs.getLong("customer_id");
        Customer c = new Customer();
        c.setId(cid);
        e.setAuthor(c);
        java.sql.Timestamp time = rs.getTimestamp("publish_time");
        LocalDateTime publishTime = time != null ? time.toLocalDateTime() : null ;
        e.setPublishTime(publishTime);
        e.setPublishAddress(rs.getString("publish_address"));
        e.setContent(rs.getString("content"));
        e.setPraise(rs.getInt("praise"));
        e.setDespise(rs.getInt("despise"));
        Long tid = rs.getLong("topic_id");
        Topic t = new Topic();
        t.setId(tid);
        e.setTopic(t);
        return e;
    }
    @Override
    public boolean save(Explain explain) {
        LocalDateTime date = explain.getPublishTime();
        java.sql.Timestamp publishtime = date == null ? null : Timestamp.valueOf(date);
        // 获取被解答话题的标识符
        Long topicId = explain.getTopic().getId();
        // 获取发布者的标识符
        Long customerId = explain.getAuthor().getId();
        Object[] param = {explain.getId(), explain.getContent(), publishtime, explain.getPublishAddress(), topicId, customerId};
        try {
            return runner.update(INSERT_ONE,param)==1;
        } catch (SQLException cause) {
            throw new RuntimeException("插入失败",cause);
        }
    }

    @Override
    public boolean update(Explain explain) {
        Object[] param = {explain.getContent(), explain.getPraise(),explain.getDespise(),explain.getId()};
        try {
            return runner.update(UPDATE_ONE,param)==1;
        } catch (SQLException cause) {
            throw new RuntimeException("更新失败",cause);
        }
    }

    @Override
    public boolean remove(Long id) {
        try {
            return runner.update(DELETE_ONE,id)==1;
        } catch (SQLException cause) {
            throw new RuntimeException("删除失败",cause);
        }
    }

    @Override
    public List<Explain> findAll() {
        ResultSetHandler<List<Explain>> rsHandler = rs -> {
            List<Explain> list = new ArrayList<>();
            while (rs.next()){
                Explain e = wrap(rs);
                list.add(e);
            }
            return list;
        };
        try {
            return runner.query(SELECT_ALL,rsHandler);
        } catch (SQLException cause) {
            throw new RuntimeException("查询失败",cause);
        }
    }

    @Override
    public Explain find(Long id) {
        ResultSetHandler<Explain> rsHandler = rs -> {
            if (rs.next()){
                Explain e = wrap(rs);
                return e;
            }
            return null;
        };
        try {
            return runner.query(SELECT_ONE,rsHandler,id);
        } catch (SQLException cause) {
            throw new RuntimeException("查询失败",cause);
        }
    }

    //根据topic_id删除
    public boolean removeByTopicId(Long topic_id) {
        try{
            int count = runner.update(DELETE_BY_TOPIC_ID,topic_id);
            return count !=-1;
        }catch (SQLException cause){
            throw new RuntimeException("删除失败",cause);
        }
    }

    public List<Explain> findByTopicId(Long topicId){
        ResultSetHandler<List<Explain>> rsHandler = rs -> {
            List<Explain> list = new ArrayList<>();
            while (rs.next()){
                Explain e = wrap(rs);
                list.add(e);
            }
            return list;
        };
        try {
            return runner.query(SELECT_TOPIC_ID,rsHandler,topicId);
        } catch (SQLException cause) {
            throw new RuntimeException("查询失败",cause);
        }
    }
    //删除客户解答解答
    public boolean eremove(Long id){
        String sql="DELETE FROM t_explains WHERE customer_id = ? ";
        try {
            return runner.update(sql,id)!=-1;
        } catch (SQLException e) {
            throw new RuntimeException("删除失败",e);
        }
    }
    //删除该用户话题下所有解答
    public boolean teremove(Long id){
        String sql="DELETE FROM t_explains WHERE topic_id IN ( SELECT id FROM t_topics WHERE customer_id = ? )";
        try {
            return runner.update(sql,id)!=-1;
        } catch (SQLException e) {
            throw new RuntimeException("删除失败",e);
        }
    }
}
